package cn.stylefeng.guns.modular.recy.controller;
/*
 */

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.StrSpliter;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.shiro.ShiroUser;
import cn.stylefeng.roses.core.base.controller.*;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.*;
import cn.stylefeng.guns.modular.recy.service.*;
import org.springframework.beans.factory.annotation.*;
import cn.stylefeng.roses.core.reqres.response.*;
import cn.stylefeng.guns.modular.recy.entity.*;
import java.io.*;
import cn.stylefeng.guns.core.common.page.*;
import com.baomidou.mybatisplus.core.metadata.*;
import com.baomidou.mybatisplus.core.conditions.*;
import cn.stylefeng.guns.modular.recy.vo.*;
import cn.stylefeng.guns.modular.recy.utils.*;
import cn.hutool.core.bean.*;

import java.time.LocalDateTime;
import java.util.stream.*;
import cn.stylefeng.guns.modular.recy.warpper.*;
import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.*;
import java.util.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.*;

@Controller
@RequestMapping({ "/orderForm" })
public class OrderFormController extends BaseController
{
    private String PREFIX;
    @Autowired
    private OrderFormService orderFormService;

    @Autowired
    private BinsService binsService;

    @Autowired
    private WechatUserService wechatUserService;

    @Autowired
    private WasteTypeService wasteTypeService;

    @Autowired
    private RegionService regionService;

    @Autowired
    private ProductExchangeService productExchangeService;

    @Autowired
    private WasteStationService wasteStationService;
    
    public OrderFormController() {
        this.PREFIX = "/modular/recy/orderForm/";
    }
    
    @RequestMapping({ "" })
    public String index() {
        return this.PREFIX + "orderForm.html";
    }
    
    @RequestMapping({ "/add" })
    public String orderFormAdd() {
        return this.PREFIX + "orderForm_add.html";
    }
    
    @RequestMapping({ "/edit" })
    public String orderFormUpdate(@RequestParam("id") final String id) {
        return this.PREFIX + "orderForm_edit.html";
    }
    
    @RequestMapping({ "/detail/{id}" })
    @ResponseBody
    public ResponseData detail(@PathVariable final String id) {
        final OrderForm orderForm = (OrderForm)this.orderFormService.getById((Serializable)id);
        return (ResponseData)ResponseData.success(orderForm);
    }
    
    @RequestMapping({ "/list" })
    @ResponseBody
    public Object list(final OrderForm orderFormQuery) {
        String userNo = this.getPara("userNo");
        if(StringUtils.isNotBlank(userNo)){
            QueryWrapper<WechatUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.lambda().eq(WechatUser::getUserNo,userNo);
            WechatUser user = this.wechatUserService.getOne(userQueryWrapper,false);
            if(user==null){
                orderFormQuery.setUserId(0l);
            }else{
                orderFormQuery.setUserId(user.getId());
            }
        }
        final QueryWrapper<OrderForm> orderFormQueryWrapper = ControllerUtil.createQuery(orderFormQuery, this.getHttpServletRequest());
        ShiroUser user = ShiroKit.getUser();
        if(!StrUtil.equals(user.getAccount(),"admin")){
            String avatar = user.getAvatar();
            if(StrUtil.isBlank(avatar)) {
                avatar = UUID.randomUUID().toString();
            }
                String[] bins = avatar.split(",");
                QueryWrapper<Bins> binsQueryWrapper = new QueryWrapper<>();
                binsQueryWrapper.lambda().in(Bins::getBinsNo,bins);
                List<Bins> list = this.binsService.list(binsQueryWrapper);
                List<Long> binIdList = list.stream().map(Bins::getId).collect(Collectors.toList());
                if(binIdList.size()<=0){
                    binIdList.add(new Long(-1));
                }
                orderFormQueryWrapper.lambda().in(OrderForm::getBinsId,binIdList);
        }

        String orderNo = orderFormQuery.getOrderNo();

        final Page<OrderForm> page = (Page<OrderForm>) LayuiPageFactory.defaultPage();
        LayuiPageInfo pageInfo = null;
        if(StringUtils.isNotBlank(orderNo)){
            OrderForm orderForm = this.orderFormService.getById(NumberUtils.toLong(orderNo));
            OrderFormVO orderFormVO = EntityBind.bind(orderForm, OrderFormVO.class);
            List<Map<String,Object>> records = new ArrayList<>();
            Map<String, Object> stringObjectMap = BeanUtil.beanToMap(orderFormVO);
            records.add(stringObjectMap);
            page.setRecords(new OrderFormWrapper(records).wrap());
            pageInfo = LayuiPageFactory.createPageInfo(page);
        }else {
            final IPage<OrderForm> page2 = (IPage<OrderForm>) this.orderFormService.page((IPage) page, (Wrapper) orderFormQueryWrapper);
            final List<OrderFormVO> orderFormVOList = EntityBind.bind(page2.getRecords(), OrderFormVO.class);
            final List<Map<String, Object>> list = orderFormVOList.stream().map(orderForm -> BeanUtil.beanToMap(orderForm)).collect(Collectors.toList());
            page2.setRecords((List) new OrderFormWrapper(list).wrap());
            pageInfo = LayuiPageFactory.createPageInfo(page2);
        }
        if (orderFormQuery.getUserId()!=null && orderFormQuery.getUserId()>0l) {
            QueryWrapper<OrderForm> userOrderFormQueryWrapper = new QueryWrapper<>();
            userOrderFormQueryWrapper.select("sum(waste_weight) as totalWeight");
            userOrderFormQueryWrapper.lambda().eq(OrderForm::getUserId,orderFormQuery.getUserId());
            Map<String, Object> map = this.orderFormService.getMap(userOrderFormQueryWrapper);
            Long totalWeight = MapUtil.getLong(map, "totalWeight");
            pageInfo.setMsg("用户："+userNo+"，总回收重量："+totalWeight+"。");
        }
        return pageInfo;
    }
    @RequestMapping("/binsList")
    @ResponseBody
    public Object binsList(){
        ShiroUser user = ShiroKit.getUser();
        List<Bins> binsList = new ArrayList<>();
        if(StrUtil.equals(user.getAccount(),"admin")){
            binsList = this.binsService.list();
        }else{
            String avatar = user.getAvatar();
            if(StrUtil.isBlank(avatar)){
                avatar = UUID.randomUUID().toString();
            }
            QueryWrapper<Bins> binsQueryWrapper = new QueryWrapper<>();
            List<String> bins = StrSpliter.splitTrim(avatar, ",", true);
            binsQueryWrapper.lambda().in(Bins::getBinsNo,bins);
            binsList = this.binsService.list(binsQueryWrapper);
        }

        return new SuccessResponseData(binsList);
    }
    
    @RequestMapping({ "/addItem" })
    @ResponseBody
    public Object add(final OrderForm orderForm) {
        this.orderFormService.save(orderForm);
        return OrderFormController.SUCCESS_TIP;
    }
    
    @RequestMapping({ "/delete" })
    @ResponseBody
    public Object delete(@RequestParam final String id) {
        this.orderFormService.removeById((Serializable)id);
        return OrderFormController.SUCCESS_TIP;
    }
    
    @RequestMapping({ "/editItem" })
    @ResponseBody
    public Object update(final OrderForm orderForm) {
        this.orderFormService.updateById(orderForm);
        return OrderFormController.SUCCESS_TIP;
    }
    
    @RequestMapping(value = { "/delItems" }, method = { RequestMethod.POST })
    @ResponseBody
    public Object delItem(@RequestBody final String[] ids) {
        this.orderFormService.removeByIds((Collection)Arrays.asList(ids));
        return OrderFormController.SUCCESS_TIP;
    }
    
    @RequestMapping({ "/show" })
    public Object show(final String id, final Model model) {
        final OrderForm orderForm = (OrderForm)this.orderFormService.getById((Serializable)id);
        final Map map = BeanUtil.beanToMap(orderForm);
        model.addAttribute("orderForm", new OrderFormWrapper(map).wrap());
        return this.PREFIX + "orderForm_show.html";
    }

    @RequestMapping({"/tongji"})
    public Object tongji(Model model){
        String area = ShiroKit.getUser().getArea();
        Region mgrRegion = null;
        String areaSearch = ShiroKit.getUser().getAreaCode() + "%";
        model.addAttribute("area",area);

        //今日订单总数
        Map<String, Object> orderFormCountMap = this.orderFormService.orderFormCount(areaSearch);
        Long todayOrderFormTotal = ObjectUtil.defaultIfNull(MapUtil.getLong(orderFormCountMap, "total"), 0l);
        model.addAttribute("todayOrderFormTotal",todayOrderFormTotal);




        //区域总人数
        QueryWrapper<WechatUser> wechatUserQueryWrapper = new QueryWrapper<>();
        wechatUserQueryWrapper.select("count(*) as total");
        if(StringUtils.isNotBlank(area)) {
            wechatUserQueryWrapper.lambda().like(WechatUser::getArea, areaSearch);
        }
        Map<String, Object> countMap  = this.wechatUserService.getMap(wechatUserQueryWrapper);
        Long total = MapUtil.getLong(countMap, "total");
        model.addAttribute("userTotal",total);

        //今日参与回收的人数
        Map<String, Object> todayUserRecyMap = this.orderFormService.todayUserRecy(areaSearch);
        Long userTotal = ObjectUtil.defaultIfNull(MapUtil.getLong(todayUserRecyMap, "userTotal"),0l);
        model.addAttribute("todayUserRecy",userTotal);

        DateTime today = new DateTime();
        {
            today = today.setField(DateField.HOUR_OF_DAY, 0);
            today = today.setField(DateField.MINUTE, 0);
            today = today.setField(DateField.SECOND, 0);
        }
        //区域今日新增会员
        wechatUserQueryWrapper.lambda().gt(WechatUser::getCreateTime,today.toJdkDate());
        Map<String, Object> todayCountMap = this.wechatUserService.getMap(wechatUserQueryWrapper);
        Long todayTotal = MapUtil.getLong(todayCountMap, "total");
        model.addAttribute("todayUserTotal",todayTotal);

        //区域会员数变化趋势
        wechatUserQueryWrapper  = new QueryWrapper<>();
        wechatUserQueryWrapper.select("DATE_FORMAT(create_time,'%Y-%m') as month,count(*) as total");
        //wechatUserQueryWrapper.lambda().likeRight(WechatUser::getArea,areaSearch);
        wechatUserQueryWrapper.eq("EXTRACT(YEAR FROM create_time)",today.getField(DateField.YEAR)).groupBy("DATE_FORMAT(create_time,'%Y-%m')");
        List<Map<String, Object>> userChangeMaps = this.wechatUserService.listMaps(wechatUserQueryWrapper);
        Map<Object, Map<String, Object>> userMonthChangeMap = userChangeMaps.stream().collect(Collectors.toMap(m -> {
            return m.get("month");
        }, m -> m));
        userChangeMaps = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            String monthNum = StringUtils.leftPad(i + "", 2, "0");
            String key = today.getField(DateField.YEAR) + "-" + monthNum;
            Object totalVal = !userMonthChangeMap.containsKey(key)?0:userMonthChangeMap.get(key).get("total");
            ImmutableMap<String, Object> statMap = ImmutableMap.of("month", monthNum, "total", totalVal);
            userChangeMaps.add(statMap);
            if(!userMonthChangeMap.containsKey(key)){
                userMonthChangeMap.put(key,statMap);
            }
        }
        model.addAttribute("userChangeMaps",userChangeMaps);

        QueryWrapper<OrderForm> orderFormQueryWrapper = new QueryWrapper<>();
        //区域今日各分类回收总重量
        //orderFormQueryWrapper.select("waste_id,sum(waste_weight) as total");
       // orderFormQueryWrapper.lambda().between(OrderForm::getCreateTime,today.toJdkDate(),today.offsetNew(DateField.DAY_OF_MONTH,1)).groupBy(OrderForm::getWasteId);
        List<Map<String, Object>> typeCountMapList = this.orderFormService.areaOrderFormByType(areaSearch);//this.orderFormService.listMaps(orderFormQueryWrapper);
        Map<Object, Map<String, Object>> typeCountMap = typeCountMapList.stream().collect(Collectors.toMap(m -> {
            return m.get("waste_id");
        }, m -> m));
        model.addAttribute("wasteTypeCountMap",typeCountMap);

        //区域各分类月回收量
        List<Map<String, Object>> typeMonthMapList = this.orderFormService.areaOrderFormByMonth(areaSearch);

        Map<Object, Map<String, Object>> monthMap = typeMonthMapList.stream().collect(Collectors.toMap(m -> {
            return m.get("month");
        }, m -> m));
        typeMonthMapList = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            String monthNum = StringUtils.leftPad(i + "", 2, "0");
            String key = today.getField(DateField.YEAR) + "-" + monthNum;
            Object totalVal = !monthMap.containsKey(key)?0:monthMap.get(key).get("total");
            ImmutableMap<String, Object> statMap = ImmutableMap.of("month", monthNum, "total", totalVal);
            typeMonthMapList.add(statMap);
            if(!monthMap.containsKey(key)){
                monthMap.put(key,statMap);
            }
        }
        model.addAttribute("monthMap",typeMonthMapList);


        //今日兑换次数
        QueryWrapper<ProductExchange> productExchangeQueryWrapper = new QueryWrapper<>();
        productExchangeQueryWrapper.select("count(*) as total");
        productExchangeQueryWrapper.lambda().between(ProductExchange::getCreateTime,today.toJdkDate(),today.offsetNew(DateField.DAY_OF_MONTH,1));
        Map<String, Object> todayProductExchangeMap = this.productExchangeService.getMap(productExchangeQueryWrapper);
        Long todayProductExchangeTotal = ObjectUtil.defaultIfNull(MapUtil.getLong(todayProductExchangeMap, "total"), 0l);
        model.addAttribute("todayProductExchangeTotal",todayProductExchangeTotal);

        //回收分类信息表
        List<WasteType> wasteTypeList = this.wasteTypeService.list();
        Map<Long, String> wasteTypeMap = new LinkedHashMap<>();
        for (WasteType wasteType : wasteTypeList) {
            wasteTypeMap.put(wasteType.getId(),wasteType.getTypeName());
        }
        //wasteTypeList.stream().collect(Collectors.toMap(WasteType::getId, WasteType::getTypeName));
        model.addAttribute("wasteTypeNameMap",wasteTypeMap);

        QueryWrapper<OrderForm> orderFormQueryWrapper1 = new QueryWrapper<>();
        {
            orderFormQueryWrapper1.select("DATE_FORMAT(create_time,'%m-%d') as dayStr,sum(waste_weight) as total,waste_id as wasteId");
            orderFormQueryWrapper1.lambda().between(OrderForm::getCreateTime, today.offsetNew(DateField.DAY_OF_MONTH, -7).toJdkDate(), today.offsetNew(DateField.DAY_OF_MONTH, 1).toJdkDate());
            orderFormQueryWrapper1.groupBy("waste_id,DATE_FORMAT(create_time,'%m-%d')");
        }
        List<Map<String, Object>> tongji7day = this.orderFormService.listMaps(orderFormQueryWrapper1);
        Map<String,Long> tongjiMap7day = new HashMap<>();
        for (Map<String, Object> tongjiMap : tongji7day) {
            String key = MapUtil.getStr(tongjiMap, "dayStr") + "-" + wasteTypeMap.get(MapUtil.getLong(tongjiMap, "wasteId"));
            tongjiMap7day.put(key,MapUtil.getLong(tongjiMap,"total"));
        }
        model.addAttribute("tongjiMap7day",tongjiMap7day);



        Long allCount = 0l;
        for (Map<String, Object> stringObjectMap : typeCountMapList) {
            allCount +=MapUtil.getLong(stringObjectMap,("total"));
        }
        model.addAttribute("allOrderCount",allCount);


        //红榜
        List<WechatUser> goodRankings = this.orderFormService.recyRankingsForToday(area, 1, "asc");
        model.addAttribute("topUser",goodRankings);



        List<WechatUser> badRankings = this.orderFormService.recyRankingsForToday(area, 0, "desc");
        model.addAttribute("bottomUser",badRankings);

        /*List<Long> topUserIdList =new ArrayList<>();
        {//红榜
            QueryWrapper<WechatUser> wechatUserQueryWrapper1 = new QueryWrapper<>();
            wechatUserQueryWrapper1.lambda().gt(WechatUser::getWithdraw, 0).orderBy(true, false, WechatUser::getWithdraw);
            Page<WechatUser> page = new Page<>();
            page.setTotal(10);
            page.setSize(10);
            IPage<WechatUser> page1 = this.wechatUserService.page(page, wechatUserQueryWrapper1);
            topUserIdList = page1.getRecords().stream().map(WechatUser::getId).collect(Collectors.toList());
            model.addAttribute("topUser", page1);
        }

        {
            QueryWrapper<WechatUser> wechatUserQueryWrapper2 = new QueryWrapper<>();
            wechatUserQueryWrapper2.lambda().notIn(WechatUser::getId,topUserIdList).orderBy(true, true, WechatUser::getWithdraw);
            Page<WechatUser> page2 = new Page<>();
            page2.setTotal(10);
            page2.setSize(10);
            IPage<WechatUser> page3 = this.wechatUserService.page(page2, wechatUserQueryWrapper2);
            model.addAttribute("bottomUser", page3);
        }*/

        String[] dateStrs = new String[8];
        dateStrs[0]=today.toString("MM-dd");
        for(int i=1;i<dateStrs.length;i++) {
            dateStrs[i] = today.offsetNew(DateField.DAY_OF_MONTH, -1*i).toString("MM-dd");
        }
        model.addAttribute("dateStrs",dateStrs);

        QueryWrapper<OrderForm> orderFormQueryWrapper2 = new QueryWrapper<>();
        orderFormQueryWrapper2.lambda().orderBy(true,false,OrderForm::getWasteId).orderBy(true,false,OrderForm::getCreateTime);
        Page<OrderForm> orderFormPage = new Page<>();
        orderFormPage.setTotal(wasteTypeMap.size()*8);
        orderFormPage.setSize(orderFormPage.getTotal());
        IPage<OrderForm> orderFormIPage = this.orderFormService.page(orderFormPage, orderFormQueryWrapper2);
        List<OrderForm> records = orderFormIPage.getRecords();
        List<OrderFormVO> orderFormVOS = EntityBind.bind(records, OrderFormVO.class);
        ArrayListMultimap<Object, Object> recentOrderFormMap = ArrayListMultimap.create();
        for (OrderFormVO orderFormVO : orderFormVOS) {
            recentOrderFormMap.put(orderFormVO.getWasteIdModel().getTypeName(),orderFormVO);
        }
        model.addAttribute("resentOrderMap",recentOrderFormMap.asMap());

        return this.PREFIX+"tongji.html";
    }



    @RequestMapping({"/tongji2"})
    public Object tongji2(Model model){
        String area = ShiroKit.getUser().getArea();
        Region mgrRegion = null;
        String areaSearch = ShiroKit.getUser().getAreaCode() + "%";
        model.addAttribute("area",area);


        QueryWrapper<WechatUser> wechatUserQueryWrapper = new QueryWrapper<>();
        wechatUserQueryWrapper.lambda().likeLeft(WechatUser::getAreaCode,ShiroKit.getUser().getAreaCode());
        int count = this.wechatUserService.count();
        model.addAttribute("areaUserCount",count);





        QueryWrapper<OrderForm> orderFormQueryWrapper = new QueryWrapper<>();
        //区域今日各分类回收总重量
        //orderFormQueryWrapper.select("waste_id,sum(waste_weight) as total");
        // orderFormQueryWrapper.lambda().between(OrderForm::getCreateTime,today.toJdkDate(),today.offsetNew(DateField.DAY_OF_MONTH,1)).groupBy(OrderForm::getWasteId);
        List<Map<String, Object>> typeCountMapList = this.orderFormService.areaOrderFormByType(areaSearch);//this.orderFormService.listMaps(orderFormQueryWrapper);
        Map<Object, Map<String, Object>> typeCountMap = typeCountMapList.stream().collect(Collectors.toMap(m -> {
            return m.get("waste_id");
        }, m -> m));
        model.addAttribute("wasteTypeCountMap",typeCountMap);












        //回收分类信息表
        List<WasteType> wasteTypeList = this.wasteTypeService.list();
        Map<Long, String> wasteTypeMap = new LinkedHashMap<>();
        for (WasteType wasteType : wasteTypeList) {
            wasteTypeMap.put(wasteType.getId(),wasteType.getTypeName());
        }
        //wasteTypeList.stream().collect(Collectors.toMap(WasteType::getId, WasteType::getTypeName));
        model.addAttribute("wasteTypeNameMap",wasteTypeMap);



        DateTime today = new DateTime();
        {
            today = today.setField(DateField.HOUR_OF_DAY, 0);
            today = today.setField(DateField.MINUTE, 0);
            today = today.setField(DateField.SECOND, 0);
        }
        //分类情况
        QueryWrapper<OrderForm> orderFormCleanQueryWrapper = new QueryWrapper<>();
        orderFormCleanQueryWrapper.select("waste_status as cleanType,count(distinct user_id) as total");
        orderFormCleanQueryWrapper.lambda()
                .between(OrderForm::getCreateTime,today,today.offsetNew(DateField.DAY_OF_MONTH,1).toJdkDate())
                .groupBy(OrderForm::getWasteStatus)
                .orderByAsc(OrderForm::getWasteStatus)
        ;
        List<Map<String, Object>> orderFormCleanMapList = this.orderFormService.listMaps(orderFormCleanQueryWrapper);
        ImmutableMap<Integer, String> cleanTypeNameMap = ImmutableMap.of(0, "合格", 1, "不合格", 2, "空桶");
        model.addAttribute("cleanTypeNameMap",cleanTypeNameMap);
        Map<Integer, Object> orderFormCleanMap = orderFormCleanMapList.stream().collect(Collectors.toMap(map -> MapUtil.getInt(map,"cleanType"), map -> map));
        model.addAttribute("orderFormCleanMap",orderFormCleanMap);

        //今日参与回收的人数
        QueryWrapper<OrderForm> orderFormForUserQueryWrapper = new QueryWrapper<>();
        orderFormForUserQueryWrapper.select("count(distinct user_id) as total");
        orderFormForUserQueryWrapper.lambda().between(OrderForm::getCreateTime,today,today.offsetNew(DateField.DAY_OF_MONTH,1).toJdkDate());
        Map<String, Object> todayRecyUserCountMap = this.orderFormService.getMap(orderFormForUserQueryWrapper);
        Long todayRecyUserCount = ObjectUtil.defaultIfNull(MapUtil.getLong(todayRecyUserCountMap, "total"),0l);
        model.addAttribute("todayRecyUserCount",todayRecyUserCount);


        String[] dateStrs = new String[8];
        dateStrs[0]=today.toString("MM-dd");
        for(int i=1;i<dateStrs.length;i++) {
            dateStrs[i] = today.offsetNew(DateField.DAY_OF_MONTH, -1*i).toString("MM-dd");
        }
        model.addAttribute("dateStrs",dateStrs);

        List<OrderForm> records = this.orderFormService.recentRecyOrderFor2day(areaSearch,  100);
//        List<OrderForm> records = orderFormIPage.getRecords();
        List<OrderFormVO> orderFormVOS = EntityBind.bind(records, OrderFormVO.class);
        ArrayListMultimap<Object, Object> recentOrderFormMap = ArrayListMultimap.create();
        for (OrderFormVO orderFormVO : orderFormVOS) {
            recentOrderFormMap.put(orderFormVO.getWasteIdModel().getTypeName(),orderFormVO);
        }
        model.addAttribute("resentOrderMap",recentOrderFormMap.asMap());


        String areaCode = ShiroKit.getUser().getAreaCode();
        if (StrUtil.isNotBlank(areaCode)) {
            QueryWrapper<WasteStation> wasteStationQueryWrapper = new QueryWrapper<>();
            wasteStationQueryWrapper.lambda().eq(WasteStation::getAreaCode,areaCode);
            List<WasteStation> list = this.wasteStationService.list(wasteStationQueryWrapper);
            model.addAttribute("wasteStationList",list);
        }
        QueryWrapper<OrderForm> orderFormQueryWrapper1 = new QueryWrapper<>();
        {
            orderFormQueryWrapper1.select("DATE_FORMAT(create_time,'%m-%d') as dayStr,sum(waste_weight) as total,waste_id as wasteId");
            orderFormQueryWrapper1.lambda().between(OrderForm::getCreateTime, today.offsetNew(DateField.DAY_OF_MONTH, -7).toJdkDate(), today.offsetNew(DateField.DAY_OF_MONTH, 1).toJdkDate());
            orderFormQueryWrapper1.groupBy("waste_id,DATE_FORMAT(create_time,'%m-%d')");
        }
        List<Map<String, Object>> tongji7day = this.orderFormService.listMaps(orderFormQueryWrapper1);
        Map<String,Long> tongjiMap7day = new HashMap<>();
        for (Map<String, Object> tongjiMap : tongji7day) {
            String key = MapUtil.getStr(tongjiMap, "dayStr") + "-" + wasteTypeMap.get(MapUtil.getLong(tongjiMap, "wasteId"));
            tongjiMap7day.put(key,MapUtil.getLong(tongjiMap,"total"));
        }
        model.addAttribute("tongjiMap7day",tongjiMap7day);

        return this.PREFIX+"tongji2.html";
    }


    @RequestMapping({"/tongji3"})
    public Object tongji3(Model model,Integer areaCodeIndex){
        String area = ShiroKit.getUser().getArea();
        Region mgrRegion = null;
        String areaSearch = ShiroKit.getUser().getAreaCode() + "%";
        model.addAttribute("area",area);

        QueryWrapper<OrderForm> orderFormQueryWrapper = new QueryWrapper<>();
        //区域今日各分类回收总重量
        //orderFormQueryWrapper.select("waste_id,sum(waste_weight) as total");
        // orderFormQueryWrapper.lambda().between(OrderForm::getCreateTime,today.toJdkDate(),today.offsetNew(DateField.DAY_OF_MONTH,1)).groupBy(OrderForm::getWasteId);
        List<Map<String, Object>> typeCountMapList = this.orderFormService.areaOrderFormByType(areaSearch);//this.orderFormService.listMaps(orderFormQueryWrapper);
        Map<Object, Map<String, Object>> typeCountMap = typeCountMapList.stream().collect(Collectors.toMap(m -> {
            return m.get("waste_id");
        }, m -> m));
        model.addAttribute("wasteTypeCountMap",typeCountMap);

        //回收分类信息表
        List<WasteType> wasteTypeList = this.wasteTypeService.list();
        Map<Long, String> wasteTypeMap = new LinkedHashMap<>();
        for (WasteType wasteType : wasteTypeList) {
            wasteTypeMap.put(wasteType.getId(),wasteType.getTypeName());
        }
        //wasteTypeList.stream().collect(Collectors.toMap(WasteType::getId, WasteType::getTypeName));
        model.addAttribute("wasteTypeNameMap",wasteTypeMap);

        DateTime today = new DateTime();
        {
            today = today.setField(DateField.HOUR_OF_DAY, 0);
            today = today.setField(DateField.MINUTE, 0);
            today = today.setField(DateField.SECOND, 0);
        }
        String[] dateStrs = new String[8];
        dateStrs[0]=today.toString("MM-dd");
        for(int i=1;i<dateStrs.length;i++) {
            dateStrs[i] = today.offsetNew(DateField.DAY_OF_MONTH, -1*i).toString("MM-dd");
        }
        model.addAttribute("dateStrs",dateStrs);

        QueryWrapper<OrderForm> orderFormQueryWrapper2 = new QueryWrapper<>();
        orderFormQueryWrapper2.lambda().orderBy(true,false,OrderForm::getWasteId).orderBy(true,false,OrderForm::getCreateTime);
        Page<OrderForm> orderFormPage = new Page<>();
        orderFormPage.setTotal(wasteTypeMap.size()*8);
        orderFormPage.setSize(orderFormPage.getTotal());
        IPage<OrderForm> orderFormIPage = this.orderFormService.page(orderFormPage, orderFormQueryWrapper2);
        List<OrderForm> records = orderFormIPage.getRecords();
        List<OrderFormVO> orderFormVOS = EntityBind.bind(records, OrderFormVO.class);
        ArrayListMultimap<Object, Object> recentOrderFormMap = ArrayListMultimap.create();
        for (OrderFormVO orderFormVO : orderFormVOS) {
            recentOrderFormMap.put(orderFormVO.getWasteIdModel().getTypeName(),orderFormVO);
        }
        model.addAttribute("resentOrderMap",recentOrderFormMap.asMap());


        String areaCode = ShiroKit.getUser().getAreaCode();
        if(StrUtil.isNotBlank(areaCode)){
            areaCodeIndex = areaCodeIndex==null?1:(areaCodeIndex%Region.AREA_CODE_INDEXS.length);
            String cityCode = areaCode.substring(0, Region.AREA_CODE_INDEXS[areaCodeIndex]);
            QueryWrapper<Region> regionQueryWrapper = new QueryWrapper<>();
            regionQueryWrapper.lambda().eq(Region::getLongcode,cityCode);
            Region region = this.regionService.getOne(regionQueryWrapper, false);
            model.addAttribute("region",region);

        }

        return this.PREFIX+"tongji3.html";
    }

    private Region getLastRegion(String params){
        String[] areas = StrUtil.split(params, ",");
        String[] regions = StrUtil.split(areas[0],"/");
        if(ObjectUtil.isNotNull(regions) && regions.length>1) {
            QueryWrapper<Region> regionQueryWrapper = new QueryWrapper<>();
            regionQueryWrapper.lambda().eq(Region::getLevel, 2).eq(Region::getName, regions[0]).or().eq(Region::getLevel, 3).eq(Region::getName, regions[1]);
            if (regions.length > 2) {
                regionQueryWrapper.lambda().or().eq(Region::getLevel, 4).eq(Region::getName, regions[2]);
            }
            regionQueryWrapper.orderByAsc("level").orderByAsc("longcode");
            List<Region> list = this.regionService.list(regionQueryWrapper);
            if (list.size() > 0) {
                Region province = list.get(0);
                list = list.stream().filter(region -> {
                    return StrUtil.startWith(region.getLongcode(), province.getLongcode());
                }).collect(Collectors.toList());
                Region lastRegion = CollectionUtil.getLast(list);
                if(areas.length>1) {
                    regionQueryWrapper = new QueryWrapper<>();
                    regionQueryWrapper.lambda().likeRight(Region::getLongcode, lastRegion.getLongcode() + "_").eq(Region::getName, areas[1]).gt(Region::getLevel,lastRegion.getLevel());
                    Region one = this.regionService.getOne(regionQueryWrapper);
                    return one;
                }
                return lastRegion;
            }
        }
        return null;
    }

    @RequestMapping("/createTestData")
    @ResponseBody
    public Object createTestData(){
        ShiroUser user = ShiroKit.getUser();
        String area = user.getArea();
        String areaCode = user.getAreaCode();
        List<OrderForm> list = this.orderFormService.list();
        DateTime nowDateTime = new DateTime();
        list.forEach(orderForm -> {
            int day = RandomUtil.randomInt(0, 7);
            Date createTime = nowDateTime.offsetNew(DateField.DAY_OF_MONTH, -1 * day).toJdkDate();
            orderForm.setCreateTime(createTime);
            orderForm.updateById();
            UpdateWrapper<WechatUser> wechatUserUpdateWrapper = new UpdateWrapper<>();
            wechatUserUpdateWrapper.lambda().set(WechatUser::getArea,area).set(WechatUser::getAreaCode,areaCode).eq(WechatUser::getId,orderForm.getUserId());
            this.wechatUserService.update(wechatUserUpdateWrapper);
        });
        return new SuccessResponseData();
    }
}
